package com.gusto.engine.spring.parsers;

import java.util.List;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;

import com.gusto.engine.semsim.measures.impl.CompoundSimilarity;
import com.gusto.engine.semsim.measures.impl.CompoundSimilarityParam;

public class ParserCompoundSimilarity extends AbstractBeanDefinitionParser {
	
	private AbstractBeanDefinition parseComposedParam(Element element, ParserContext parserContext) {
		BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(CompoundSimilarityParam.class);
		
		if (element.hasAttribute("name")) {
			String property = element.getAttribute("name");
			beanDefinitionBuilder.addPropertyValue("name", property);
		}
		if (element.hasAttribute("property")) {
			String property = element.getAttribute("property");
			beanDefinitionBuilder.addPropertyValue("property", property);
		}
		
		return beanDefinitionBuilder.getBeanDefinition();
	}
	
	@SuppressWarnings("unchecked")
	protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
		BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(CompoundSimilarity.class);
		
		if (element.hasAttribute("similarity")) {
			String similarity = element.getAttribute("similarity");
			beanDefinitionBuilder.addPropertyReference("similarity", similarity);
		}
		
		List childElements = DomUtils.getChildElementsByTagName(element, "property");
		//List<ComposedSimilarityParam> params = new ArrayList<ComposedSimilarityParam>();
		ManagedList children = new ManagedList(childElements.size());
		
		for (int i = 0; i < childElements.size(); ++i) {
	         Element childElement = (Element) childElements.get(i);
	         BeanDefinition child = parseComposedParam(childElement, parserContext);
	         children.add(child);
	    }
		beanDefinitionBuilder. addPropertyValue("properties", children);
		return beanDefinitionBuilder.getBeanDefinition();
	}
	
}
